package com.horizon.manage.device.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.horizon.common.constrants.HorizonResultCodeEnum;
import com.horizon.common.controller.HorizonBaseController;
import com.horizon.common.util.HorizonUtil;
import com.horizon.manage.device.converter.DeviceEvdConverter;
import com.horizon.manage.device.dto.DeviceDto;
import com.horizon.manage.device.entity.Device;
import com.horizon.manage.device.service.IDeviceService;
import com.horizon.manage.device.vo.DeviceVO;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 设备controller.
 *
 * @author zhaoshb
 * @since 2022/12/4 21:04
 */
@RestController
@AllArgsConstructor
@RequestMapping("/horizon/device")
public class DeviceController extends HorizonBaseController {

    private IDeviceService deviceService;
    private DeviceEvdConverter deviceEvdConverter;

    @PostMapping("/create")
    @ApiOperation(value = "创建", notes = "创建")
    public R<Long> create(@RequestBody DeviceDto deviceDto) {
        Device device = deviceEvdConverter.dtoToEntity(deviceDto);
        boolean saved = deviceService.save(device);
        return saved ? R.data(device.getId()) : R.fail(ResultCode.FAILURE);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除", notes = "删除")
    public R<Object> delete(@RequestBody Long deviceId) {
        int rowAffected = deviceService.getBaseMapper().deleteById(deviceId);
        return rowAffected == 1 ? R.data(null) : R.fail(HorizonUtil.getLocaleMessage(HorizonResultCodeEnum.DEVICE_NOT_EXIST));
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新", notes = "更新")
    public R<Object> update(@RequestBody DeviceDto dto) {
        Device device = deviceEvdConverter.dtoToEntity(dto);
        return R.status(deviceService.updateById(device));
    }

    @GetMapping("/list")
    @ApiOperation(value = "分页", notes = "传入cond以及排序条件")
    public R<IPage<DeviceVO>> list(@ApiIgnore @RequestParam Map<String, Object> cond, Query query) {
        IPage<Device> pages = deviceService.page(Condition.getPage(query), Condition.getQueryWrapper(cond, Device.class));
        return R.data(deviceEvdConverter.pageVO(pages));
    }

}
